﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Blog.DTO.BlogTeamMember;
using AnQinFrameWorkAPI.Entity.Blog.Entity;
using AnQinFrameWorkAPI.Entity.Blog.View.BlogTeamMember;
using AutoMapper;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.Blog;

/// <summary>
///     团队成员服务
/// </summary>
public class BlogTeamMemberService
{
    private readonly DatabaseContext _context;
    private readonly IMapper _mapper;

    /// <summary>
    ///     构造函数（依赖注入）
    /// </summary>
    public BlogTeamMemberService(DatabaseContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    #region 获取团队成员列表（分页）

    /// <summary>
    ///     获取团队成员列表（分页）
    /// </summary>
    public async Task<RequestResponseModel> GetBlogTeamMemberList(BlogTeamMemberSearchDTO searchDTO)
    {
        //sql
        var sql = @"
                SELECT
                    Id,
                    Code,
                    Name,
                    SuperiorId,
                    SuperiorName,
                    Order,
                    IsDelete,
                    CreateTime
                FROM
                    Department
                WHERE
                    IsDelete = 0
            ";

        var query = _context.Database.SqlQueryRaw<BlogTeamMemberView>(sql)
            .AsQueryable()
            .WhereIF(a => a.Code.Contains(searchDTO.Code), !string.IsNullOrEmpty(searchDTO.Code))
            .WhereIF(a => a.Name.Contains(searchDTO.Name), !string.IsNullOrEmpty(searchDTO.Name))
            .WhereIF(a => a.Title.Contains(searchDTO.Title), !string.IsNullOrEmpty(searchDTO.Title))
            .WhereIF(a => a.CreateTime > searchDTO.StartTime, searchDTO.StartTime != null)
            .WhereIF(a => a.CreateTime < searchDTO.EndTime, searchDTO.EndTime != null);

        var list = await query
            .OrderByDescending(a => a.CreateTime)
            .Page(searchDTO.PageIndex, searchDTO.PageSize)
            .ToListAsync();

        var totalCount = await query.CountAsync();

        return RequestResponse.OK(new PageResult<BlogTeamMemberView>(list, totalCount), "查询成功");
    }

    #endregion

    #region 新增团队成员

    /// <summary>
    ///     新增团队成员
    /// </summary>
    public async Task<RequestResponseModel> AddBlogTeamMember(BlogTeamMemberAddDTO addDTO)
    {
        var entity = _mapper.Map<BlogTeamMemberModel>(addDTO);
        entity.Id = Guid.NewGuid();
        entity.CreateTime = DateTime.Now;

        _context.BlogTeamMember.Add(entity);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(entity.Id, "新增成功");
    }

    #endregion

    #region 更新团队成员

    /// <summary>
    ///     更新团队成员
    /// </summary>
    public async Task<RequestResponseModel> PutBlogTeamMember(BlogTeamMemberUpdateDTO updateDTO)
    {
        var existing = await Valid.ValidId(_context.BlogTeamMember, updateDTO.Id);
        if (existing == null)
            return RequestResponse.ErrorRequest("团队成员ID无效");

        _mapper.Map(updateDTO, existing);
        _context.BlogTeamMember.Update(existing);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(updateDTO.Id, "更新成功");
    }

    #endregion

    #region 删除团队成员

    /// <summary>
    ///     删除团队成员
    /// </summary>
    public async Task<RequestResponseModel> DeleteBlogTeamMember(SingleIdDTO deleteDTO)
    {
        var entity = await Valid.ValidId(_context.BlogTeamMember, deleteDTO.Id);
        if (entity == null)
            return RequestResponse.ErrorRequest("团队成员ID无效");

        _context.BlogTeamMember.Remove(entity);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion
}